import axios from 'axios'
import ViewUIPlus from 'view-ui-plus'

const req = axios.create({
  baseURL: '/api', /* 自己项目中请求地址前缀部分 */
  timeout: 60000, /* 请求超时时间毫秒 */
  withCredentials: true, /* 异步请求携带cookie */
  headers: {
    // 设置后端需要的传参类型
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest',
  },
})

export const post = (url, data) => req({
  url,
  method: 'post',
  data,
})

export const get = (url, params) => req({
  url,
  method: 'get',
  params,
})

req.interceptors.request.use(
  (config) => {
    // 根据不同文档返回不同的密码
    if (config.params?.document_id) {
      config.headers.Key = localStorage.getItem(`document_key_${config.params?.document_id}`)
    }
    return config
  },
  (error) => Promise.reject(error)
)

// 添加响应拦截器
req.interceptors.response.use(
  (response) => {
    const dataAxios = response.data
    if (dataAxios.code === 0) {
      ViewUIPlus.Message.error({
        render: (h) => h('span', [dataAxios.msg])
      })
      return Promise.reject(response)
    }

    return dataAxios
  },
  (error) => {
    ViewUIPlus.Message.error({
      background: true,
      render: (h) => h('span', [error.msg])
    })
    return Promise.reject(error)
  }
)

export default req
